package com.corejsf;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

@Named
@SuppressWarnings("serial")
@ApplicationScoped
/**
 * Stores all the users in the system.
 * @author Jitin Dhillon, Kelton Kowalchuk
 *
 */
public class Credentials implements Serializable{
    /**
     * Variable to keep track of highest id for adding new users.
     */
	public static int highid = 0;
	/**
	 * System List of users.
	 */
	public static ArrayList<User> users = new ArrayList<User>();
	
	public static ArrayList<User> getCredentials() { return users; }
	public static void setCredentials(ArrayList<User> credentials) { Credentials.users = credentials; }
	
	public static int getHighid() {	return highid; }
	public static void setHighid(int highid) { Credentials.highid = highid; }
	
	/**
	 * Returns all the users in the users table from the worksheets database
	 */
	public static void getUsers(){
		users.clear();
		PreparedStatement stmt = null;
		Connection connection = null;
		DataSource dataSource = null;
		Context ctx = null;
		try {
			String strDSName = "java:jboss/datasources/worksheets";
			ctx = new InitialContext();
			dataSource = (javax.sql.DataSource) ctx.lookup(strDSName);
			try {
				connection = dataSource.getConnection();
				stmt = connection
						.prepareStatement("SELECT * FROM users");
				try {
					ResultSet rs = stmt.executeQuery();
					while (rs.next()) {
						int eNum = rs.getInt("eNumber");
						String fullName = rs.getString("FullName");
						String username = rs.getString("UserName");
						String password = rs.getString("Password");
						boolean superuser = rs.getBoolean("Superuser");
						User user = new User(fullName, username, password, eNum);
						user.setSuperUser(superuser);
						users.add(user);
						if(eNum >= highid){
							highid = eNum + 1;
						}
					}
				} finally {
					if (stmt != null) {
						stmt.close();
					}
				}
			} finally {
				if (connection != null) {
					connection.close();
				}
			}
		} catch (SQLException ex) {
			System.out.println("Error in persist ");
			ex.printStackTrace();
		} catch (NamingException e) {
			System.out.println("Naming Exception");
			e.printStackTrace();
		}
	}
	
	/**
	 * Increments the highid variable.
	 */
	public void setIncrement(){
		highid++;
	}
}
